import axios from "axios";
import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

const $http = axios.create({
      baseURL: "/api",
});

// 请求拦截
$http.interceptors.request.use((config: any) => {
      const token = localStorage.getItem("token");
      if (token) {
            config.headers.common["Authorization"] = "Bearer " + token;
      }

      return config;
});

// 响应拦截
$http.interceptors.response.use((response) => {
      const { data } = response;

      if (data.code === -666) {
            ElMessageBox.confirm(data.message, "过期", {
                  confirmButtonText: "登录",
                  showCancelButton: false,
                  type: "warning",
            }).then(() => {
                  const router = useRouter();
                  localStorage.removeItem("token");
                  console.log(router);
                  router.replace("/login");
            });
      }

      return data;
});

export { $http };
